import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../../constants.dart';
import '../../../models/user_account_alloc_entity.dart';
import '../../../theme.dart';
import '../../../widget/null_tip.dart';
import 'logic.dart';

class FundPage extends StatelessWidget {
  FundPage({Key? key}) : super(key: key);

  final FundLogic logic = Get.put(FundLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('专款'),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back(result: true);
          },
        ),
      ),
      body: Obx(() {
        if (logic.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        } else if (logic.depositList.isEmpty) {
          return const NullTip();
        } else {
          return RefreshIndicator(
            onRefresh: () async => logic.reload(),
            child: ListView.builder(
                controller: logic.scrollController,
                itemBuilder: _renderRow,
                itemCount: logic.depositList.length + 2),
          );
        }
      }),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index == 0) {
      return _buildDepositBg(children: [
        Text(
          '总额(元)',
          style: TextStyle(
            fontSize: kFontSizeMini,
            color: AppColor.colorFontBlack,
          ),
        ),
        SizedBox(height: kSpaceSmall),
        Obx(
          () => Text(
            logic.deposit.value.replaceAll('¥', ''),
            style: TextStyle(
              fontSize: 44.sp,
              fontWeight: AppFont.fontSemiBold,
            ),
          ),
        ),
        SizedBox(height: kSpaceMedium),
        // Row(children: [
        //   FilledButton(
        //     style: FilledButton.styleFrom(
        //       backgroundColor: AppColor.colorBtnGrey,
        //       padding: EdgeInsets.symmetric(vertical: 14.w),
        //       shape: RoundedRectangleBorder(
        //         borderRadius: BorderRadius.circular(kRadiusMedium),
        //       ),
        //     ),
        //     onPressed: () => logic.onClickWithdraw(),
        //     child: Text(
        //       '提现',
        //       style: TextStyle(
        //         fontSize: kFontSizeMedium,
        //         color: AppColor.colorFontBlack,
        //       ),
        //     ),
        //   ),
        //   FilledButton(
        //     style: FilledButton.styleFrom(
        //       backgroundColor: AppColor.colorFontBlue,
        //       padding: EdgeInsets.symmetric(vertical: 14.w),
        //       shape: RoundedRectangleBorder(
        //         borderRadius: BorderRadius.circular(kRadiusMedium),
        //       ),
        //     ),
        //     onPressed: () {
        //       if (!logic.commonService.isAssistant()) {}
        //     },
        //     child: Text(
        //       '转账',
        //       style: TextStyle(
        //         fontSize: kFontSizeMedium,
        //         color: Colors.white,
        //       ),
        //     ),
        //   ),
        // ]),

        _buildButtons(),
      ]);
    } else if (index < logic.depositList.length + 1) {
      int i = index - 1;
      return Padding(
        padding: EdgeInsets.only(
            left: kSpaceSmall, right: kSpaceSmall, bottom: kSpaceMedium),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(kSpaceSmall)),
          child: Material(
            color: Colors.white,
            child: InkWell(
              onTap: () => logic.onClickItem(logic.depositList[i]),
              child: _buildListItem(logic.depositList[i]),
            ),
          ),
        ),
      );
    } else {
      return _getMoreWidget();
    }
  }

  Widget _buildButtons() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Expanded(
          child: FilledButton(
            style: FilledButton.styleFrom(
              backgroundColor: AppColor.colorBtnGrey,
              padding: EdgeInsets.symmetric(vertical: 14.w),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(kRadiusMedium),
              ),
            ),
            onPressed: () => logic.onClickWithdraw(),
            child: Text(
              '提现',
              style: TextStyle(
                fontSize: kFontSizeMedium,
                color: AppColor.colorFontBlack,
              ),
            ),
          ),
        ),
        SizedBox(width: kSpaceMedium),
        Expanded(
          child: FilledButton(
            style: FilledButton.styleFrom(
              backgroundColor: AppColor.colorFontBlue,
              padding: EdgeInsets.symmetric(vertical: 14.w),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(kRadiusMedium),
              ),
            ),
            onPressed: () {
              if (!logic.commonService.isAssistant()) {
                logic.onClickFundRecord();
              }
            },
            child: Text(
              '查看专款明细',
              style: TextStyle(
                fontSize: kFontSizeMedium,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildListItem(UserAccountAllocData item) {
    return Padding(
      padding: EdgeInsets.all(kSpaceSmall),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: _itemBuilder(item),
      ),
    );
  }

  List<Widget> _itemBuilder(UserAccountAllocData item) {
    return [
      logic.role.value == 'man'
          ? _buildItem('创建人', item.agentUsername)
          : Container(),
      logic.role.value == 'man' ? SizedBox(height: kSpaceLarge) : Container(),
      _buildItem('专款金额', '${item.orderAmount} (余额: ¥${item.availableAmount})'),
      SizedBox(height: kSpaceLarge),
      _buildItem(
          '产生时间',
          item.updatedAt == 0
              ? ''
              : DateFormat('yyyy-MM-dd HH:mm:ss')
                  .format(DateTime.fromMillisecondsSinceEpoch(item.updatedAt))),
      SizedBox(height: kSpaceLarge),
      _buildItem(
          '关联案件', item.invoiceObj.relateCases.map((e) => e.caseName).join(',')),
    ];
  }

  Widget _buildItem(String title, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontBlack,
          ),
        ),
        SizedBox(width: kSpaceLarge),
        Expanded(
          child: Text(
            value,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.right,
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
        )
      ],
    );
  }

  Widget _buildDepositBg({required List<Widget> children}) {
    return Container(
      width: double.maxFinite,
      margin: EdgeInsets.all(kSpaceSmall),
      padding:
          EdgeInsets.symmetric(horizontal: kSpaceSmall, vertical: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        children: children,
      ),
    );
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.only(bottom: kSpaceMedium),
        child: Text(
          logic.bottomTips.value,
          style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
        ),
      ),
    );
  }
}
